package shop

import (
	"encoding/json"
	"github.com/beego/beego/v2/core/logs"
	"yixiang.co/yshop/controllers"
	"yixiang.co/yshop/models"
	"yixiang.co/yshop/models/dto"
	"yixiang.co/yshop/models/vo"
)

// 商品规格sku api
type StoreProductRuleController struct {
	controllers.BaseController
}

func (c *StoreProductRuleController) URLMapping() {
	c.Mapping("Post", c.Post)
	c.Mapping("GetAll", c.GetAll)
	c.Mapping("Put", c.Put)
	c.Mapping("Delete", c.Delete)
}

// @Title 商品规格sku列表
// @Description 商品规格sku列表
// @Success 200 {object} controllers.Result
// @router / [get]
func (c *StoreProductRuleController) GetAll() {
	enabled, _ := c.GetInt64("enabled", -1)
	total, list := models.GetAllProductRule(c.GetParams(), enabled)
	c.Ok(vo.ResultList{Content: list, TotalElements: total})
}

// @Title 商品规格sku添加
// @Description 商品规格sku添加
// @Success 200 {object} controllers.Result
// @router /save/:id [post]
func (c *StoreProductRuleController) Post() {
	id, _ := c.GetInt64(":id", 0)
	var (
		dto   dto.ProductRule
		model *models.YshopStoreProductRule
		e     error
	)
	json.Unmarshal(c.Ctx.Input.RequestBody, &dto)
	jsonstr, _ := json.Marshal(dto.RuleValue)
	ruleValue := string(jsonstr)
	c.Valid(&dto)
	if id > 0 {
		model = &models.YshopStoreProductRule{
			Id:        id,
			RuleName:  dto.RuleName,
			RuleValue: ruleValue,
		}
		e = models.UpdateByProductRule(model)
	} else {
		model = &models.YshopStoreProductRule{
			RuleName:  dto.RuleName,
			RuleValue: ruleValue,
		}
		_, e = models.AddProductRule(model)
	}

	if e != nil {
		c.Fail(e.Error(), 5002)
	}
	c.Ok("操作成功")
}

// @Title 商品规格sku修改
// @Description 商品规格sku修改
// @Success 200 {object} controllers.Result
// @router / [put]
func (c *StoreProductRuleController) Put() {
	var model models.YshopStoreProductRule
	json.Unmarshal(c.Ctx.Input.RequestBody, &model)
	c.Valid(&model)
	e := models.UpdateByProductRule(&model)
	if e != nil {
		c.Fail(e.Error(), 5004)
	}
	c.Ok("操作成功")
}

// @Title 商品规格sku删除
// @Description 商品规格sku删除
// @Success 200 {object} controllers.Result
// @router / [delete]
func (c *StoreProductRuleController) Delete() {
	var ids []int64
	json.Unmarshal(c.Ctx.Input.RequestBody, &ids)
	logs.Info(ids)
	e := models.DelByProductRulee(ids)
	if e != nil {
		c.Fail(e.Error(), 5005)
	}
	c.Ok("操作成功")
}
